﻿using Marmat.Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Marmat.Template.WinForm
{
    /// <summary>
    /// 基于内存的通知服务总线。
    /// </summary>
    public class MemoryNotificationBus : Marmat.Foundation.INotificationBus
    {
        private readonly List<KeyValuePair<string, INotification>> collection = new List<KeyValuePair<string, INotification>>();

        public void Publish(string channel, params object[] arguments)
        {
            var items = collection.Where(x => x.Key == channel && x.Value is not null);
            foreach (var item in items)
            {
                if (item.Value is System.Windows.Forms.Control control && control.IsDisposed)
                    this.Unsubscribe(item.Value);
                else
                    item.Value.ReceiveNotification(channel, arguments);
            }
        }

        public void Subscription(string channel, INotification notification)
        {
            collection.Add(new KeyValuePair<string, INotification>(channel, notification));
        }

        public void Unsubscribe(INotification notification)
        {
            collection.RemoveAll(x => x.Value == notification);
        }
    }
}
